﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using Model;
using BLL;
using System.Data;

public partial class EWM_demo : WeiPage
{

    QMActivityBO qbo = new QMActivityBO();
    QMPersonBO qmbo = new QMPersonBO();
    PersonInfoBO pbo = new PersonInfoBO();
    WeiXinRequestBO wb = new WeiXinRequestBO();
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["FromUserName"] = "oVKRtuEmDWLI7Vi6MFAd_KVP5b3g";

        if (!IsPostBack)
        {
            try
            {

                Session["X"] = "121.459441";
                Session["Y"] = "31.224461";
                if (Request.QueryString["code"] != null)
                {
                    try
                    {
                        string url = string.Format(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + GetAppid() + "&secret=" + GetSecret() + "&code={0}&grant_type=authorization_code", Request.QueryString["code"].ToString());
                        string token = PostRequest(url);
                        if (token.Contains("7200"))
                        {
                            string[] b = token.Split('\"');
                            Session["FromUserName"] = b[13];
                            Session["ToUserName"] = GetAppid();
                        }
                    }
                    catch (Exception)
                    {

                    }
                }

            }
            catch (Exception)
            {

            }
            QMPerson qmper = qmbo.GetModel(Session["FromUserName"].ToString());
            if (qmper != null)
            {
                //string re = "";
                Response.Redirect("wd.aspx?mdname=" + qmper.MdName);
                //AlertMessage("您已领取过");
            }
           

            QMPerson qmper1 = qmbo.GetModel3(Session["FromUserName"].ToString());
            if (qmper1 != null)
            {
                string Access_token = Token();
                var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""您已完成申领，无法再次申请。""
    }
}";
                d = d.Replace("{0}", Session["FromUserName"].ToString());

                var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);
                return;
               
            }
            //DataSet set = qbo.GetAllList();
            //if (set != null)
            //{
            //    if (set.Tables[0].Rows.Count > 0)
            //    {
            //        for (int i = 0; i < set.Tables[0].Rows.Count; i++)
            //        { 

            //        }
 
            //    }
            //}

        }

        try
        {
            if (!IsPostBack)
            {

                if ((Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null) && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
                {
                    string user = Request.QueryString["FromUserName"] == null ? Session["FromUserName"].ToString() : Request.QueryString["FromUserName"].ToString();
                    string user2 = Request.QueryString["ToUserName"] == null ? Session["ToUserName"].ToString() : Request.QueryString["ToUserName"].ToString();
                    List<WeiXinRequest> list = wb.GetModelList(string.Format(" Wxevent='location' AND FromUserName='{0}' ORDER BY id DESC ", user));
                    if (list.Count == 0)
                    {

                        Session["X"] = "121.459441";
                        Session["Y"] = "31.224461";
                    }
                    else
                    {

                        Session["X"] = list[0].Location_X;
                        Session["Y"] = list[0].Location_Y;
                        WebClient client = new WebClient();
                        string url2 = "http://maps.google.com/maps/api/geocode/xml?latlng=" + list[0].Location_X + "," + list[0].Location_Y + "&language=zh-CN&sensor=false";
                        client.Encoding = Encoding.UTF8;
                        string responseTest = client.DownloadString(url2);
                        if (responseTest.Contains("上海"))
                        {
                            ddlcity.SelectedValue = "上海";
                        }
                        else if (responseTest.Contains("成都"))
                        {
                            ddlcity.SelectedValue = "成都";
                        }
                        else if (responseTest.Contains("北京"))
                        {
                            ddlcity.SelectedValue = "北京";
                        }
                        else
                        {
                            ddlcity.SelectedValue = "上海";
                        }
                        ddlcity_SelectedIndexChanged(null, null);



                    }
                }

            }
        }
        catch (Exception)
        {

        }

    }


    protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlmd.Items.Clear();
        ddlmd.Items.Add(new ListItem("请选择柜台", "-1"));
        if (ddlcity.SelectedValue == "上海")
        {
            ddlmd.Items.Add(new ListItem("和平饭店店", "10001"));
            ddlmd.Items.Add(new ListItem("田子坊店", "10002"));
            ddlmd.Items.Add(new ListItem("嘉里店", "10003"));
            ddlmd.Items.Add(new ListItem("虹口龙之梦店", "10004"));
            ddlmd.Items.Add(new ListItem("环球金融店", "10005"));
            ddlmd.Items.Add(new ListItem("米格天地店", "10006"));

            se.InnerHtml = string.Format(@"<ul>
     <li><bdo>根据您搜索的关键词找到以下专柜地址</bdo></li>
      <li>
       <h2>
       和平饭店店</h2>
       <p>黄浦区南京东路20号北楼</p>
       <p><span><a  onclick='return dj(""和平饭店店"",""{0}"")'>在线申请</a></span><strong>021-33663536</strong></p>
      </li>

<li>
       <h2>
       田子坊店</h2>
       <p>徐汇区泰康路210弄3号</p>
       <p><span><a  onclick='return dj(""田子坊店"",""{1}"")'>在线申请</a></span><strong>021-64159901</strong></p>
      </li>



<li>
       <h2>
       嘉里店</h2>
       <p>浦东新区花木路1378号1层129号商铺</p>
       <p><span><a  onclick='return dj(""嘉里店"",""{2}"")'>在线申请</a></span><strong>021-50173686</strong></p>
      </li>

<li>
       <h2>
       虹口龙之梦店</h2>
       <p>虹口区西江湾路388号，凯德龙之梦虹口广场(A)02层27号</p>
       <p><span><a  onclick='return dj(""虹口龙之梦店"",""{3}"")'>在线申请</a></span><strong>021-32050120</strong></p>
      </li>

<li>
       <h2>
       环球金融店</h2>
       <p>浦东新区世纪大道100号2号楼216-2区域</p>
       <p><span><a  onclick='return dj(""环球金融店"",""{4}"")'>在线申请</a></span><strong>021-68365030</strong></p>
      </li>

<li>
       <h2>
       米格天地店</h2>
       <p>青浦区嘉松公路5999号米格天地A-1210商铺</p>
       <p><span><a  onclick='return dj(""米格天地店"",""{5}"")'>在线申请</a></span><strong>021-39299619</strong></p>
      </li>

   </ul>
    <br />", "10001", "10002", "10003", "10004", "10005", "10006");


        }
        else if (ddlcity.SelectedValue == "北京")
        {
            ddlmd.Items.Add(new ListItem("凯德晶品店", "20001"));
            ddlmd.Items.Add(new ListItem("世贸天阶店", "20002"));
            ddlmd.Items.Add(new ListItem("金地店", "20003"));
            se.InnerHtml = string.Format(@"<ul>
     <li><bdo>根据您搜索的关键词找到以下专柜地址</bdo></li>
      <li>
       <h2>
       凯德晶品店</h2>
       <p>海淀区复兴路51号凯德晶品店3层14号</p>
       <p><span><a  onclick='return dj(""凯德晶品店"",""{0}"")'>在线申请</a></span><strong>010-68260095</strong></p>
      </li>

<li>
       <h2>
       世贸天阶店</h2>
       <p>朝阳区光华路9号世贸天阶中心1号楼2层L223(永安里北大街芳草地站下车既是)</p>
       <p><span><a  onclick='return dj(""世贸天阶店"",""{1}"")'>在线申请</a></span><strong>010-65871386</strong></p>
      </li>

<li>
       <h2>
       金地店</h2>
       <p>朝阳区建国路91号金地时代中心C座2层L208单元</p>
       <p><span><a  onclick='return dj(""金地店"",""{2}"")'>在线申请</a></span><strong>010-85713517</strong></p>
      </li>

   </ul>
    <br />", "20001", "20002", "20004");


        }
        else if (ddlcity.SelectedValue == "成都")
        {
            ddlmd.Items.Add(new ListItem("来福士店", "30001"));
            ddlmd.Items.Add(new ListItem("茂业春熙店", "30002"));
            ddlmd.Items.Add(new ListItem("茂业天地店", "30003"));
            se.InnerHtml = string.Format(@"<ul>
     <li><bdo>根据您搜索的关键词找到以下专柜地址</bdo></li>
      <li>
       <h2>
       来福士店</h2>
       <p>武侯区人民南路四段3号来福士广场L1层1015号</p>
       <p><span><a  onclick='return dj(""来福士店"",""{0}"")'>在线申请</a></span><strong>028-85571580</strong></p>
      </li>
<li>
       <h2>
       茂业春熙店</h2>
       <p>锦江区总府路12号一层</p>
       <p><span><a  onclick='return dj(""茂业春熙店"",""{1}"")'>在线申请</a></span><strong>028-86718261</strong></p>
      </li>
<li>
       <h2>
       茂业天地店</h2>
       <p>锦江区东御街19号一层</p>
       <p><span><a  onclick='return dj(""茂业天地店"",""{2}"")'>在线申请</a></span><strong>&nbsp;</strong></p>
      </li>


   </ul>
    <br />", "30004", "30002", "30003");

        }
        else
        {
            AlertMessage("请选择城市");
            return;
        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

        int city = 0;
        if (ddlcity.SelectedValue == "-1")
        {
            AlertMessage("请选择城市");
        }
        else if (ddlcity.SelectedValue == "上海")
        {
            city = 1;

        }
        else if (ddlcity.SelectedValue == "北京")
        {
            city = 2;

        }
        else if (ddlcity.SelectedValue == "成都")
        {
            city = 3;

        }
        if (ddlcity.SelectedValue != "-1")
        {

            QMActivity qm = qbo.GetModel(city, mdname.Value);
            DataSet ds = qmbo.GetMD(ddlcity.SelectedValue, mdname.Value);
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > int.Parse(qm.Count))
                {
                    AlertMessage("本店领取名额已发完，请选择其他门店");

                }
                else
                {
                    if (ddlcity.SelectedValue == "-1")
                    {
                        AlertMessage("请选择城市");
                    }

                    else
                    {
                        if (Request.QueryString["FromUserName"] != null || Session["FromUserName"] != null && (Request.QueryString["ToUserName"] != null || Session["ToUserName"] != null))
                        {
                            string user = Session["FromUserName"].ToString(); //这里需要修改 
                            //string user = Request.QueryString["FromUserName"].ToString();
                            PersonInfo per = pbo.GetModel(user);
                            string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Token() + "&openid=" + user;
                            string b = PostRequest(url);
                            string[] a = b.Split('\"');
                            if (a.Length != 35)
                            {
                                Response.Redirect("http://mp.weixin.qq.com/s?__biz=MjM5NDc2MjQyMQ==&mid=200470016&idx=1&sn=43bae3fe639a2980a840bfa8cf47beaf#rd");
                                return;
                            }
                            if (per != null)
                            {
                                QMPerson qmper = qmbo.GetModel2(user);
                                if (qmper != null)
                                {
                                    Response.Redirect("wd.aspx?mdname=" + qmper.MdName);
                                    //AlertMessage("只能选择一个门店进行领取");
                                }
                                else
                                {
                                    QMPerson qmperson = new QMPerson();
                                    qmperson.City = ddlcity.SelectedValue;
                                    qmperson.FromuserName = user;
                                    //这里需要修改
                                    qmperson.MdKey = int.Parse(key.Value);
                                    qmperson.MdName = mdname.Value;
                                    qmperson.Status = 0;
                                    int count = qmbo.Add(qmperson);
                                    if (count > 0)
                                    {
                                        AlertMessage("领取成功");
                                        string Access_token = Token();
                                        var postUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_token;
                                        string d = @"{
    ""touser"":""{0}"",
    ""msgtype"":""text"",
    ""text"":
    {
         ""content"":""您已经获得{2}{1}申领资格，请于5月4号前（含5月4日）到{2}{1}领取您的雙妹3+2+1明星产品试用组。""
    }
}";
                                        d = d.Replace("{0}", user).Replace("{1}", mdname.Value).Replace("{2}",ddlcity.SelectedValue);
                                        var resMessage = HttpXmlPostRequest(postUrl, d, Encoding.UTF8);
                                    }
                                }

                            }
                            else
                            {
                                AlertMessage("请先注册或绑定");

                            }
                        }
                        else
                        {
                            AlertMessage("您还未关注雙妹公众账号");
                        }
                    }

                }
            }
        }
    }



    public void AlertMessage(string message)
    {
        if (message.Equals("请先注册或绑定"))
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='../MembershipCard/wechat_web/index2.aspx';</script>");
        }
        else if (message.Equals("领取成功"))
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");window.location.href='wd.aspx?mdname=" + mdname.Value + "';</script>");

        }

        else
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alertCloseReload", "<script>alert(\"" + message + "\");</script>");
        }
    }



}